<?php
session_start();
require_once '../includes/config.php';
require_once '../includes/database.php';
require_once '../includes/auth.php';
require_once '../includes/attendance.php';

// 检查权限
$auth = getAuth();
$auth->requirePermission('super_admin');

// 获取当前用户信息
$currentUser = $auth->getCurrentUser();

// 获取统计数据
$db = getDB();
$attendance = getAttendance();

// 今日考勤统计
$today = date('Y-m-d');
$todayStats = $db->querySingle("
    SELECT 
        COUNT(*) as total_users,
        SUM(CASE WHEN (morning_clock_in IS NOT NULL OR afternoon_clock_in IS NOT NULL) THEN 1 ELSE 0 END) as clocked_in,
        SUM(CASE WHEN status = 'late' THEN 1 ELSE 0 END) as late_count,
        SUM(CASE WHEN status = 'absent' THEN 1 ELSE 0 END) as absent_count
    FROM attendance_records 
    WHERE record_date = ?
", [$today]);

// 月度统计
$currentMonth = date('Y-m');
$monthStats = $db->querySingle("
    SELECT 
        COUNT(DISTINCT user_id) as active_users,
        AVG(total_work_hours) as avg_hours,
        SUM(CASE WHEN status = 'late' THEN 1 ELSE 0 END) as total_late,
        SUM(CASE WHEN status = 'absent' THEN 1 ELSE 0 END) as total_absent
    FROM attendance_records 
    WHERE record_date LIKE ?
", ["{$currentMonth}%"]);

// 最近考勤记录
$recentRecords = $db->query("
    SELECT ar.*, u.full_name, u.department 
    FROM attendance_records ar 
    JOIN users u ON ar.user_id = u.id 
    WHERE ar.record_date = ? 
    ORDER BY ar.morning_clock_in DESC, ar.afternoon_clock_in DESC 
    LIMIT 10
", [$today]);

// 用户统计
$userStats = $db->querySingle("
    SELECT 
        COUNT(*) as total_users,
        SUM(CASE WHEN role = 'super_admin' THEN 1 ELSE 0 END) as admin_count,
        SUM(CASE WHEN role = 'user' THEN 1 ELSE 0 END) as user_count,
        SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as active_users
    FROM users
");
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员仪表板 - 考勤管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- 侧边栏 -->
    <?php include_once '../includes/sidebar.php'; ?>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 顶部导航 -->
        <nav class="navbar navbar-expand navbar-custom mb-4">
            <div class="container-fluid">
                <div class="navbar-nav me-auto">
                    <span class="navbar-text">
                        <i class="fas fa-home me-2"></i>管理员仪表板
                    </span>
                </div>
                <div class="navbar-nav">
                    <span class="navbar-text me-3">
                        <i class="fas fa-user me-2"></i>
                        <?php echo htmlspecialchars($currentUser['full_name']); ?>
                    </span>
                    <a href="../user/profile.php" class="nav-link">
                        <i class="fas fa-cog"></i> 个人设置
                    </a>
                </div>
            </div>
        </nav>

        <!-- 统计卡片 -->
        <div class="row mb-4">
            <div class="col-md-3 mb-3">
                <div class="card stat-card border-primary">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title text-primary">今日打卡</h5>
                                <h2 class="text-primary"><?php echo $todayStats['clocked_in'] ?? 0; ?></h2>
                                <p class="card-text text-muted">/ <?php echo $todayStats['total_users'] ?? 0; ?> 人</p>
                            </div>
                            <div class="stat-icon text-primary">
                                <i class="fas fa-user-check"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3 mb-3">
                <div class="card stat-card border-warning">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title text-warning">今日迟到</h5>
                                <h2 class="text-warning"><?php echo $todayStats['late_count'] ?? 0; ?></h2>
                                <p class="card-text text-muted">迟到人数</p>
                            </div>
                            <div class="stat-icon text-warning">
                                <i class="fas fa-clock"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3 mb-3">
                <div class="card stat-card border-danger">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title text-danger">今日缺勤</h5>
                                <h2 class="text-danger"><?php echo $todayStats['absent_count'] ?? 0; ?></h2>
                                <p class="card-text text-muted">缺勤人数</p>
                            </div>
                            <div class="stat-icon text-danger">
                                <i class="fas fa-user-times"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3 mb-3">
                <div class="card stat-card border-success">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title text-success">平均工时</h5>
                                <h2 class="text-success"><?php echo round($monthStats['avg_hours'] ?? 0, 1); ?></h2>
                                <p class="card-text text-muted">本月平均</p>
                            </div>
                            <div class="stat-icon text-success">
                                <i class="fas fa-chart-line"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- 用户统计 -->
            <div class="col-md-6 mb-4">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-users me-2"></i>用户统计
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row text-center">
                            <div class="col-6">
                                <h3 class="text-primary"><?php echo $userStats['total_users'] ?? 0; ?></h3>
                                <small class="text-muted">总用户数</small>
                            </div>
                            <div class="col-6">
                                <h3 class="text-success"><?php echo $userStats['active_users'] ?? 0; ?></h3>
                                <small class="text-muted">活跃用户</small>
                            </div>
                        </div>
                        <hr>
                        <div class="row text-center">
                            <div class="col-6">
                                <h4 class="text-info"><?php echo $userStats['admin_count'] ?? 0; ?></h4>
                                <small class="text-muted">管理员</small>
                            </div>
                            <div class="col-6">
                                <h4 class="text-secondary"><?php echo $userStats['user_count'] ?? 0; ?></h4>
                                <small class="text-muted">普通用户</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 快速操作 -->
            <div class="col-md-6 mb-4">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-bolt me-2"></i>快速操作
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="d-grid gap-2">
                            <a href="users.php" class="btn btn-outline-primary">
                                <i class="fas fa-user-plus me-2"></i>添加用户
                            </a>
                            <a href="attendance_enhanced.php" class="btn btn-outline-warning">
                                <i class="fas fa-edit me-2"></i>考勤管理
                            </a>
                            <a href="reports.php" class="btn btn-outline-info">
                                <i class="fas fa-download me-2"></i>导出报表
                            </a>
                            <a href="config.php" class="btn btn-outline-secondary">
                                <i class="fas fa-cogs me-2"></i>系统设置
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- 日历视图 -->
            <div class="col-md-8 mb-4">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-calendar me-2"></i>本月考勤日历
                        </h5>
                    </div>
                    <div class="card-body">
                        <?php
                        // 获取当前月的考勤数据
                        $currentMonth = date('Y-m');
                        $monthRecords = $db->query("
                            SELECT ar.*, u.full_name, u.department 
                            FROM attendance_records ar 
                            JOIN users u ON ar.user_id = u.id 
                            WHERE ar.record_date LIKE ? 
                            ORDER BY ar.record_date, u.full_name
                        ", ["{$currentMonth}%"]);
                        
                        // 按日期分组
                        $recordsByDate = [];
                        foreach ($monthRecords as $record) {
                            $date = $record['record_date'];
                            if (!isset($recordsByDate[$date])) {
                                $recordsByDate[$date] = [];
                            }
                            $recordsByDate[$date][] = $record;
                        }
                        
                        // 生成日历
                        $year = date('Y');
                        $month = date('m');
                        $firstDay = date('w', strtotime("$year-$month-01"));
                        $daysInMonth = date('t', strtotime("$year-$month-01"));
                        ?>
                        
                        <div class="calendar-header text-center mb-3">
                            <h4><?php echo date('Y年m月'); ?></h4>
                        </div>
                        
                        <div class="calendar">
                            <div class="calendar-weekdays row text-center fw-bold">
                                <div class="col p-2 border">日</div>
                                <div class="col p-2 border">一</div>
                                <div class="col p-2 border">二</div>
                                <div class="col p-2 border">三</div>
                                <div class="col p-2 border">四</div>
                                <div class="col p-2 border">五</div>
                                <div class="col p-2 border">六</div>
                            </div>
                            
                            <div class="calendar-days row">
                                <?php
                                // 填充空白
                                for ($i = 0; $i < $firstDay; $i++) {
                                    echo '<div class="col p-2 border bg-light"></div>';
                                }
                                
                                // 填充日期
                                for ($day = 1; $day <= $daysInMonth; $day++) {
                                    $date = sprintf('%s-%02d', $currentMonth, $day);
                                    $isToday = $date === date('Y-m-d');
                                    $hasRecords = isset($recordsByDate[$date]);
                                    $dayRecords = $hasRecords ? $recordsByDate[$date] : [];
                                    
                                    // 统计当天的考勤状态
                                    $statusCounts = [
                                        'normal' => 0,
                                        'late' => 0,
                                        'early_leave' => 0,
                                        'absent' => 0,
                                        'leave' => 0,
                                        'business_trip' => 0
                                    ];
                                    
                                    foreach ($dayRecords as $record) {
                                        $status = $record['status'];
                                        if (isset($statusCounts[$status])) {
                                            $statusCounts[$status]++;
                                        }
                                    }
                                    
                                    // 确定主要状态（用于颜色显示）
                                    $mainStatus = 'normal';
                                    if ($statusCounts['absent'] > 0) {
                                        $mainStatus = 'absent';
                                    } elseif ($statusCounts['leave'] > 0) {
                                        $mainStatus = 'leave';
                                    } elseif ($statusCounts['business_trip'] > 0) {
                                        $mainStatus = 'business_trip';
                                    } elseif ($statusCounts['late'] > 0 || $statusCounts['early_leave'] > 0) {
                                        $mainStatus = 'late';
                                    }
                                    
                                    $statusColors = [
                                        'normal' => 'bg-success',
                                        'late' => 'bg-warning',
                                        'absent' => 'bg-danger',
                                        'leave' => 'bg-info',
                                        'business_trip' => 'bg-primary'
                                    ];
                                    
                                    $bgClass = $hasRecords ? $statusColors[$mainStatus] : '';
                                    $todayClass = $isToday ? 'today' : '';
                                    
                                    echo '<div class="col p-2 border calendar-day ' . $todayClass . ' ' . $bgClass . '">';
                                    echo '<div class="day-number">' . $day . '</div>';
                                    
                                    if ($hasRecords) {
                                        $totalUsers = count($dayRecords);
                                        $presentUsers = 0;
                                        foreach ($dayRecords as $record) {
                                            if ($record['morning_clock_in'] || $record['afternoon_clock_in']) {
                                                $presentUsers++;
                                            }
                                        }
                                        
                                        echo '<div class="attendance-stats">' . $presentUsers . '/' . $totalUsers . '</div>';
                                    }
                                    
                                    echo '</div>';
                                    
                                    // 换行
                                    if (($firstDay + $day) % 7 == 0 && $day < $daysInMonth) {
                                        echo '</div><div class="row">';
                                    }
                                }
                                
                                // 填充剩余空白
                                $remainingDays = (7 - (($firstDay + $daysInMonth) % 7)) % 7;
                                for ($i = 0; $i < $remainingDays; $i++) {
                                    echo '<div class="col p-2 border bg-light"></div>';
                                }
                                ?>
                            </div>
                        </div>
                        
                        <div class="calendar-legend mt-3">
                            <small class="text-muted">
                                <span class="badge bg-success me-2">正常</span>
                                <span class="badge bg-warning me-2">迟到/早退</span>
                                <span class="badge bg-danger me-2">缺勤</span>
                                <span class="badge bg-info me-2">请假</span>
                                <span class="badge bg-primary me-2">出差</span>
                                <span class="text-muted">数字表示：出勤人数/总人数</span>
                            </small>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 最近考勤记录 -->
            <div class="col-md-4 mb-4">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-history me-2"></i>今日最新考勤记录
                        </h5>
                    </div>
                    <div class="card-body">
                        <?php if (empty($recentRecords)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-inbox fa-3x mb-3"></i>
                                <p>今日暂无考勤记录</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>姓名</th>
                                            <th>状态</th>
                                            <th>时间</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($recentRecords as $record): ?>
                                        <tr>
                                            <td>
                                                <div><?php echo htmlspecialchars($record['full_name']); ?></div>
                                                <small class="text-muted"><?php echo htmlspecialchars($record['department']); ?></small>
                                            </td>
                                            <td>
                                                <?php
                                                $statusLabels = [
                                                    'normal' => '<span class="badge bg-success">正常</span>',
                                                    'late' => '<span class="badge bg-warning">迟到</span>',
                                                    'early_leave' => '<span class="badge bg-warning">早退</span>',
                                                    'absent' => '<span class="badge bg-danger">缺勤</span>',
                                                    'leave' => '<span class="badge bg-info">请假</span>',
                                                    'business_trip' => '<span class="badge bg-primary">出差</span>'
                                                ];
                                                echo $statusLabels[$record['status']] ?? '<span class="badge bg-secondary">未知</span>';
                                                ?>
                                            </td>
                                            <td>
                                                <?php 
                                                $morningIn = $record['morning_clock_in'] ?: '--';
                                                $afternoonIn = $record['afternoon_clock_in'] ?: '--';
                                                echo "上午: {$morningIn}<br>下午: {$afternoonIn}";
                                                ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
